import pandas as pd
import os

# 设置显示选项，使其更易读
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 1000)
pd.set_option('display.max_colwidth', 100)

class DictionaryData:
    def __init__(self):
        # 当前目录
        self.current_dir = os.path.dirname(os.path.abspath(__file__))
        
        # 加载数据
        print("正在加载数据...")
        self.word_df = pd.read_csv(os.path.join(self.current_dir, 'word.csv'), sep='>')
        self.word_translation_df = pd.read_csv(os.path.join(self.current_dir, 'word_translation.csv'))
        self.book_df = pd.read_csv(os.path.join(self.current_dir, 'book.csv'), sep='>')
        self.relation_df = pd.read_csv(os.path.join(self.current_dir, 'relation_book_word.csv'), sep='>')
        
        # 创建索引以提高查询效率
        self.word_df.set_index('vc_id', inplace=True)
        self.word_translation_df.set_index('word', inplace=True)
        self.book_df.set_index('bk_id', inplace=True)
        
        print("数据加载完成!")
        print(f"- 单词表: {len(self.word_df)}个单词")
        print(f"- 单词翻译: {len(self.word_translation_df)}个翻译")
        print(f"- 单词书: {len(self.book_df)}本")
        print(f"- 单词书-单词关系: {len(self.relation_df)}条")
        print()
    
    def search_word(self, word):
        """搜索单词信息及翻译"""
        print(f"\n搜索单词: {word}")
        
        # 查找单词信息
        word_info = self.word_df[self.word_df['vc_vocabulary'] == word]
        
        if not word_info.empty:
            print("单词信息:")
            print(f"- 单词: {word}")
            print(f"- 英音音标: {word_info['vc_phonetic_uk'].values[0]}")
            print(f"- 美音音标: {word_info['vc_phonetic_us'].values[0]}")
            print(f"- 词频: {word_info['vc_frequency'].values[0]}")
            print(f"- 难度: {word_info['vc_difficulty'].values[0]}")
            print(f"- 认识率: {word_info['vc_acknowledge_rate'].values[0]}")
        else:
            print("未找到该单词的详细信息")
        
        # 查找翻译
        if word in self.word_translation_df.index:
            translation = self.word_translation_df.loc[word, 'translation']
            print(f"\n翻译:")
            print(f"- {translation}")
        else:
            print("未找到该单词的翻译")
    
    def list_books(self, level=None):
        """列出单词书"""
        print("\n可用的单词书:")
        
        books = self.book_df.copy()
        if level is not None:
            books = books[books['bk_level'] == level]
        
        # 显示部分信息
        for idx, row in books.head(10).iterrows():
            print(f"- {row['bk_name']} (单词数: {row['bk_item_num']})")
        
        if len(books) > 10:
            print(f"... 还有 {len(books) - 10} 本单词书未显示")
    
    def get_words_from_book(self, book_name, limit=10):
        """获取指定单词书中的单词"""
        print(f"\n单词书 '{book_name}' 中的单词:")
        
        # 查找单词书ID
        book = self.book_df[self.book_df['bk_name'].str.contains(book_name, na=False)]
        
        if book.empty:
            print(f"未找到名为 '{book_name}' 的单词书")
            return
        
        book_id = book.index[0]
        book_info = book.iloc[0]
        print(f"- 书名: {book_info['bk_name']}")
        print(f"- 总单词数: {book_info['bk_item_num']}")
        print(f"- 作者: {book_info['bk_author']}")
        print(f"- 出版社: {book_info['bk_publisher']}")
        
        # 查找该单词书中的单词
        book_words = self.relation_df[self.relation_df['bv_book_id'] == book_id]
        
        # 获取单词信息
        result_words = []
        for idx, row in book_words.head(limit).iterrows():
            if row['bv_voc_id'] in self.word_df.index:
                word_info = self.word_df.loc[row['bv_voc_id']]
                word = word_info['vc_vocabulary']
                phonetic_us = word_info['vc_phonetic_us']
                
                # 获取翻译
                translation = "未找到翻译"
                if word in self.word_translation_df.index:
                    translation = self.word_translation_df.loc[word, 'translation']
                
                result_words.append({
                    'word': word,
                    'phonetic': phonetic_us,
                    'translation': translation,
                    'unit': row['bv_tag'],
                    'order': row['bv_order']
                })
        
        # 按顺序排序并显示
        result_words.sort(key=lambda x: x['order'])
        for item in result_words:
            print(f"{item['order']}. {item['word']} {item['phonetic']} - {item['translation']} ({item['unit']})")
    
    def find_high_frequency_words(self, limit=10):
        """查找高频单词"""
        print("\n高频单词 (按词频排序):")
        
        high_freq_words = self.word_df.sort_values('vc_frequency', ascending=False).head(limit)
        
        for idx, row in high_freq_words.iterrows():
            word = row['vc_vocabulary']
            frequency = row['vc_frequency']
            
            # 获取翻译
            translation = "未找到翻译"
            if word in self.word_translation_df.index:
                translation = self.word_translation_df.loc[word, 'translation']
            
            print(f"- {word} (词频: {frequency}) - {translation}")

# 使用示例
if __name__ == "__main__":
    dict_data = DictionaryData()
    
    # 示例1: 搜索单词
    dict_data.search_word("apple")
    
    # 示例2: 列出单词书
    dict_data.list_books()
    
    # 示例3: 获取指定单词书中的单词
    # 这里可以替换为你感兴趣的单词书名称
    first_book_name = dict_data.book_df.iloc[0]['bk_name']
    dict_data.get_words_from_book(first_book_name)
    
    # 示例4: 查找高频单词
    dict_data.find_high_frequency_words()